﻿#pragma once
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
	class Date
	{
		friend ostream& operator << (ostream& out, const Date& d);
		friend istream& operator >> (istream& in, Date& d);
	public:
		Date(int year = 1, int month = 1, int day = 1)
			:_year(year)
			, _month(month)
			, _day(day)
		{
		}
	private:
		int _year;
		int _month;
		int _day;
	};
	istream& operator >> (istream& in, Date& d)
	{
		in >> d._year >> d._month >> d._day;
		return in;
	}
	ostream& operator << (ostream& out, const Date& d)
	{
		out << d._year << " " << d._month << " " << d._day << endl;
		return out;
	}
	struct ServerInfo
	{
		// ⼆进制读写时，这⾥不能⽤string，
		// 否则写到⽂件中的是string中指向字符数组的指针
		// 若string对象析构后再去⽂件中读取string对象，string中读到是⼀个野指针。
		char _address[32];
		//string _address;
		int _port;
		Date _date;
	};
	struct ConfigManager
	{
	public:
		ConfigManager(const char* filename)
			:_filename(filename)
		{
		}
		//二进制写
		// 内存中怎么存，囫囵吞枣，就怎么直接写出去

		void WriteBin(const ServerInfo& info)
		{
			ofstream ofs(_filename, ios_base::out | ios_base::binary);
			ofs.write((const char*)&info, sizeof(info));
		}
		//⼆进制读

		// 将⽂件中的内容直接囫囵吞枣，直接读到内存中

		void ReadBin(ServerInfo& info)
		{
			ifstream ifs(_filename, ios_base::in | ios_base::binary);
			ifs.read((char*)&info, sizeof(info));
		}
		void WriteText(const ServerInfo& info)
		{
			ofstream ofs(_filename);
			ofs << info._address << " " << info._port << " " << info._date;
		}
		void ReadText(ServerInfo& info)
		{
			ifstream ifs(_filename);
			ifs >> info._address >> info._port >> info._date;
		}
	private:
		string _filename; 
		// 	配置⽂件
	};
	void writeBin()
	{
		ServerInfo winfo = { "192.0.0.1111111111111111111111", 80, { 2025, 1, 10 }};
		//⼆进制读写

		ConfigManager cf_bin("test.bin");
		cf_bin.WriteBin(winfo);
	}
	void readBin()
	{
		// ⼆进制读写

		ConfigManager cf_bin("test.bin");
		ServerInfo rbinfo;
		cf_bin.ReadBin(rbinfo);
		cout << rbinfo._address << " " << rbinfo._port << " " 
			<< rbinfo._date <<endl;
	}
	//void writeText()
	//{
	//	ServerInfo winfo = { "192.0.0.1", 80, { 2025, 1, 10 } };
	//	//⽂本读写

	//	ConfigManager cf_text("test.txt");
	//	cf_text.WriteText(winfo);
	//}
	/*void readText()
	{
		ConfigManager cf_text("test.txt");
		ServerInfo rtinfo;
		cf_text.ReadText(rtinfo);
		cout << rtinfo._address << " " << rtinfo._port << " " << rtinfo._date <<
			endl;
	}*/
	void writeText()
	{
		ServerInfo winfo = { "192.0.0.1", 80, { 2025, 1, 10 } };
		// ⽂本读写

		ConfigManager cf_text("test.txt");
		cf_text.WriteText(winfo);
	}
	void readText()
	{
		ConfigManager cf_text("test.txt");
		ServerInfo rtinfo;
		cf_text.ReadText(rtinfo);
		cout << rtinfo._address << " " << rtinfo._port << " " 
			<< rtinfo._date <<endl;
	}